package com.member.common.utils;

import com.itextpdf.text.*;
import com.itextpdf.text.pdf.*;
import com.member.common.utils.file.FileUploadUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.text.DecimalFormat;
import java.util.*;
import java.util.List;

public class PdfUtils {
    /**
     * @param fields
     * @param data
     * @throws IOException
     * @throws DocumentException
     */
    private static void fillData(AcroFields fields, Map<String, Object> data) throws IOException, DocumentException {
        List<String> keys = new ArrayList<String>();
        Map<String, AcroFields.Item> formFields = fields.getFields();
        BaseFont bf = BaseFont.createFont("AlibabaPuHuiTi-2-45-Light.ttf", BaseFont.IDENTITY_H, BaseFont.EMBEDDED);
        Font font = new Font(bf, 10f);
        font.setColor(BaseColor.BLACK);
        for (String key : data.keySet()) {
            if (formFields.containsKey(key)) {
                String value = data.get(key).toString();
                fields.setFieldProperty(key, "textfont", bf, null);
                fields.setFieldProperty(key,"textsize",10f,null);
                fields.setField(key, value); // 为字段赋值,注意字段名称是区分大小写的
                keys.add(key);
            }
        }
        Iterator<String> itemsKey = formFields.keySet().iterator();
        while (itemsKey.hasNext()) {
            String itemKey = itemsKey.next();
            if (!keys.contains(itemKey)) {
                fields.setField(itemKey, " ");
            }
        }
    }

    /**
     * @param templatePdfName 模板pdf名称
     * @param generatePdfPath 生成pdf路径
     * @param data            数据
     */
    public static String generatePDF(String templatePdfName, String generatePdfPath, String fileName, Map<String, Object> data) {
        OutputStream fos = null;
        ByteArrayOutputStream bos = null;
        try {
            byte[] bytes = generatePDF(templatePdfName, data);
            fos = Files.newOutputStream(Paths.get(generatePdfPath + fileName));
            assert bytes != null;
            fos.write(bytes);
            fos.flush();
            return generatePdfPath;
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (fos != null) {
                try {
                    fos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return null;
    }

    /**
     * @param templatePdfName 模板pdf名称
     * @param data            数据
     */
    public static byte[] generatePDF(String templatePdfName, Map<String, Object> data) {
        ByteArrayOutputStream bos = null;
        try {
            InputStream istemplate = PdfUtils.class.getClassLoader().getResourceAsStream(templatePdfName);
            assert istemplate != null;
            PdfReader reader = new PdfReader(istemplate);
            bos = new ByteArrayOutputStream();
            /* 将要生成的目标PDF文件名称 */
            PdfStamper ps = new PdfStamper(reader, bos);
            /* 使用中文字体 */
            BaseFont bf = BaseFont.createFont("AlibabaPuHuiTi-2-45-Light.ttf", BaseFont.IDENTITY_H, BaseFont.EMBEDDED);
            Font font = new Font(bf, 10f);
            font.setColor(BaseColor.BLACK);
            ArrayList<BaseFont> fontList = new ArrayList<BaseFont>();
            fontList.add(bf);
            /* 取出报表模板中的所有字段 */
            AcroFields fields = ps.getAcroFields();
            fields.setSubstitutionFonts(fontList);
            fillData(fields, data);
            /* 必须要调用这个，否则文档不会生成的  如果为false那么生成的PDF文件还能编辑，一定要设为true*/
            ps.setFormFlattening(true);
            ps.close();

            reader = new PdfReader(bos.toByteArray());
            Rectangle pageSize = reader.getPageSize(1);
            Document document = new Document(pageSize);
            PdfWriter writer = PdfWriter.getInstance(document, bos);
            document.open();
            PdfContentByte cbUnder = writer.getDirectContentUnder();
            PdfImportedPage pageTemplate = writer.getImportedPage(reader, 1);
            cbUnder.addTemplate(pageTemplate, 0, 0);

            // start
//            BaseFont baseFont1 = BaseFont.createFont("AlibabaPuHuiTi-2-45-Light.ttf",BaseFont.IDENTITY_H,BaseFont.EMBEDDED);
//            Font songti09 = new Font(baseFont1, 12f);
//            songti09.setColor(BaseColor.BLACK);

            PdfPTable table = new PdfPTable(new float[]{240, 240});
            com.itextpdf.text.List list4 = new com.itextpdf.text.List(true);
            list4.setAutoindent(true);
            list4.setNumbered(true);
            //表格数据
            DecimalFormat df = new DecimalFormat("0.00");
            List table1 = (List) data.get("table");
            for (Object o : table1) {
                PdfPCell value1 = new PdfPCell(new Phrase(o.toString(), font));
                value1.setFixedHeight(160F / (table1.size() / 2));
                value1.setVerticalAlignment(PdfPCell.ALIGN_MIDDLE);//设置单元格的垂直对齐方式
                value1.setNoWrap(false);
                value1.setHorizontalAlignment(Element.ALIGN_CENTER);//设置单元格的水平对齐方式
                table.addCell(value1);
            }
            table.setTotalWidth(495F);

            /**
             * rowStart         0   起始行
             * rowEnd           -1  表示全部行
             * xPos             表格横坐标- 从左向右开始计算
             * yPos             表格纵坐标- 从下向上开始计算
             * canvas           画布
             */
            table.writeSelectedRows(0, -1, 50, 857, cbUnder);
            //新创建一页来存放后面生成的表格
//            document.newPage();

            //动态拼接表格
//            appendTableToDocument(document, cbUnder);
            document.close();
            writer.close();
            /**********************************编辑填充后的pdf end******************************/
            return bos.toByteArray();
            // return bos;
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (bos != null) {
                try {
                    bos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return null;
    }

    private static void appendTableToDocument(Document document, PdfContentByte cbUnder) {
        //定义 6列的表格
        PdfPTable table = new PdfPTable(new float[]{80, 80, 80, 80, 80, 80});
        table.setTotalWidth(1000);
        table.setLockedWidth(true);
        table.setHorizontalAlignment(Element.ALIGN_CENTER);//居中
        table.writeSelectedRows(0, -1, 60, 2000, cbUnder);


        try {
            //定义数据的字体
            BaseFont baseFont = BaseFont.createFont("Helvetica", "UTF-8", BaseFont.NOT_EMBEDDED);
            Font textFont = new Font(baseFont, 20, Font.NORMAL);
            textFont.setColor(BaseColor.RED);

            //表头模拟数据
            for (int i = 0; i < 6; i++) {
                PdfPCell heardCell = new PdfPCell();
                heardCell.setVerticalAlignment(Element.ALIGN_MIDDLE);
                heardCell.setHorizontalAlignment(Element.ALIGN_CENTER);
                heardCell.setPhrase(new Phrase("value", textFont));
                table.addCell(heardCell);
            }
            //表格数据
            DecimalFormat df = new DecimalFormat("0.00");
            for (int i = 0; i < 1000; i++) {
                PdfPCell value1 = new PdfPCell();
                value1.setPhrase(new Phrase("2022" + i, textFont));
                table.addCell(value1);
                Double value = Math.random() * 10;
                PdfPCell value2 = new PdfPCell();
                value2.setPhrase(new Phrase(df.format(value), textFont));

            }
//            document.add(table);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    public static void exportPDF(HttpServletResponse response, String fileName, byte[] pdfBytes) throws IOException {
        if (StringUtils.isBlank(fileName)) {
            //当前日期
            fileName = DateUtils.dateTime(new Date());
        }
        response.setCharacterEncoding("UTF-8");
        response.setHeader("content-Type", "application/octet-stream");
        response.setHeader("Content-Disposition",
                "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8") + ".pdf");
        ServletOutputStream out = response.getOutputStream();
        out.write(pdfBytes);
        out.flush();
    }

//    public static void main(String[] args) {
//        Map<String, String> data = new HashMap<String, String>();
//        data.put("zbsh", "0212-7468458525");
//        data.put("userName", "和尚");
//        data.put("userPhone", "17602928773");
//        data.put("userMail", "28786118989@163.com");
//        data.put("userAddress", "asdasdasddasd");
//        data.put("buyDate", "234234");
//        data.put("warranyDate", "3456345345345");
//        data.put("proCode", "2222");
//        data.put("proText", "dsfdsfccs");
//        generatePDF("zbs.pdf",
//                "/Users/wangxin/Desktop/" , DateUtils.dateTime(new Date()) + ".pdf", data);
//    }

    public static void main(String[] args) throws IOException {
        File f = new File("/Users/wangxin/Desktop/ssssss.txt");
        MultipartFile multipartFile = FileUploadUtils.fileToMultipartFile(f);
        String path = FileUploadUtils.upload(multipartFile);
        System.out.println(path);
        boolean delete = f.delete();
    }
}
